import sha1 from 'sha1'
import store from '@/store'

export function createApiSign (appSecret = '', body) {
  const data = { ...body }
  const keyArr = Object.keys(data).sort()
  const kv = []
  for (let i = 0; i < keyArr.length; i++) {
    if (data.hasOwnProperty(keyArr[i])) {
      if (data[keyArr[i]] === undefined) {
        continue
      }
      kv.push(keyArr[i] + data[keyArr[i]])
    }
  }
  return sha1(`${kv.join('')}${appSecret}`).toLowerCase()
};
/*
 * 动态引入script跨域
*/
export function createJsCrossOrigin (url, callback) {
  let script = document.createElement('script');
  script.crossOrigin = 'true';
  script.type = 'text/javascript';
  if (typeof callback !== 'undefined') {
    if (script.readyState) {
      script.onreadystatechange = function () {
        if (script.readyState === 'loaded' || script.readyState === 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else {
      script.onload = function () {
        callback();
      };
    }
  }
  script.src = url;
  document.body.appendChild(script);
};

export function computedDistance (distance) {
	if (!distance) return ''
	let lastDistance = ''
	if (Number(distance) >= 1) {
		if (/\./.exec(distance)) {
			lastDistance = `${Number(distance).toFixed(2)}km`
		} else {
			lastDistance = `${distance}km`
		}
	} else {
		lastDistance = `${(distance * 1000).toFixed(0)}m`
	}
	return lastDistance
}

export function spliceCommonAgrs (uri = '') {
	let originUri = uri
	let [path, querys = ''] = uri.split('?')
	if (store.state.commonAgrs.pid) {
		if (querys) {
			querys = `pid=${store.state.commonAgrs.pid}&${querys}`
		} else {
			querys = `pid=${store.state.commonAgrs.pid}`
		}
		originUri = `${path}?${querys}`
	}
	return originUri
}